import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:skeletonizer/skeletonizer.dart';
import '../../../core/viewmodels/contacts_viewmodel.dart';
import '../../../core/utils/error_handler_extension.dart';
import '../../../core/constants/app_constants.dart';
import '../../../shared/widgets/error_widget.dart';
import '../../../shared/widgets/cached_avatar.dart';
import '../../../shared/widgets/skeleton_loader.dart';

class ContactsPage extends StatefulWidget {
  const ContactsPage({super.key});

  @override
  State<ContactsPage> createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  @override
  void initState() {
    super.initState();
    // 延迟加载，确保 token 已保存完成
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      // 等待一小段时间，确保 token 已保存
      await Future.delayed(const Duration(milliseconds: 100));
      if (mounted) {
        context.read<ContactsViewModel>().loadFriends();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('联系人'),
        automaticallyImplyLeading: false, // 禁用回退按钮
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.person_add_outlined),
            onPressed: () {
              // TODO: 添加好友功能
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('添加好友功能开发中')),
              );
            },
          ),
        ],
      ),
      body: Consumer<ContactsViewModel>(
        builder: (context, viewModel, child) {
          if (viewModel.isLoading && viewModel.friends.isEmpty) {
            return Skeletonizer(
              enabled: true,
              child: ListView.builder(
                padding: const EdgeInsets.symmetric(vertical: 8),
                itemCount: 5,
                itemBuilder: (context, index) => const ListItemSkeleton(),
              ),
            );
          }

          if (viewModel.hasError && viewModel.friends.isEmpty) {
            return AppErrorWidget(
              error: viewModel.errorMessage!,
              onRetry: () {
                viewModel.clearError();
                viewModel.loadFriends();
              },
            );
          }

          if (viewModel.friends.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.people_outline,
                    size: 64,
                    color: Colors.grey[400],
                  ),
                  const SizedBox(height: 16),
                  Text(
                    '暂无联系人',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey[600],
                    ),
                  ),
                  const SizedBox(height: 24),
                  ElevatedButton.icon(
                    onPressed: () => viewModel.refresh(),
                    icon: const Icon(Icons.refresh),
                    label: const Text('刷新'),
                  ),
                ],
              ),
            );
          }

          return EasyRefresh(
            onRefresh: () async {
              await viewModel.refresh();
            },
            child: ListView.builder(
              padding: const EdgeInsets.symmetric(vertical: 8),
              itemCount: viewModel.friends.length,
              itemBuilder: (context, index) {
                final friend = viewModel.friends[index];
                return Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: () {
                      // 点击联系人，跳转到聊天详情页面
                      Navigator.of(context).pushNamed(
                        AppConstants.routeChatDetail,
                        arguments: friend,
                      );
                    },
                    child: Container(
                      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 12,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: Colors.grey.shade200,
                          width: 0.5,
                        ),
                      ),
                      child: Row(
                        children: [
                          CachedAvatar(
                            imageUrl: friend.avatar,
                            name: friend.displayName,
                            size: 50,
                            borderRadius: 10,
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  friend.displayName,
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 16,
                                    color: Colors.black87,
                                  ),
                                ),
                                if (friend.remark != null || friend.nickname != null) ...[
                                  const SizedBox(height: 4),
                                  Text(
                                    friend.username,
                                    style: TextStyle(
                                      color: Colors.grey[600],
                                      fontSize: 14,
                                    ),
                                  ),
                                ],
                              ],
                            ),
                          ),
                          PopupMenuButton<String>(
                            itemBuilder: (context) => [
                              const PopupMenuItem(
                                value: 'chat',
                                child: Row(
                                  children: [
                                    Icon(Icons.chat, size: 20),
                                    SizedBox(width: 8),
                                    Text('发送消息'),
                                  ],
                                ),
                              ),
                              const PopupMenuItem(
                                value: 'delete',
                                child: Row(
                                  children: [
                                    Icon(Icons.delete, color: Colors.red, size: 20),
                                    SizedBox(width: 8),
                                    Text('删除好友', style: TextStyle(color: Colors.red)),
                                  ],
                                ),
                              ),
                            ],
                            onSelected: (value) async {
                              if (value == 'chat') {
                                // 跳转到聊天详情页面
                                Navigator.of(context).pushNamed(
                                  AppConstants.routeChatDetail,
                                  arguments: friend,
                                );
                              } else if (value == 'delete') {
                                final confirmed = await showDialog<bool>(
                                  context: context,
                                  builder: (context) => AlertDialog(
                                    title: const Text('确认删除'),
                                    content: Text('确定要删除好友 ${friend.displayName} 吗？'),
                                    actions: [
                                      TextButton(
                                        onPressed: () => Navigator.pop(context, false),
                                        child: const Text('取消'),
                                      ),
                                      TextButton(
                                        onPressed: () => Navigator.pop(context, true),
                                        child: const Text('删除', style: TextStyle(color: Colors.red)),
                                      ),
                                    ],
                                  ),
                                );

                                if (confirmed == true) {
                                  final success = await viewModel.removeFriend(friend.userId);
                                  
                                  if (!mounted) return;
                                  
                                  if (success) {
                                    context.showSuccess('删除成功');
                                  } else {
                                    context.showError(viewModel.errorMessage ?? '删除失败');
                                  }
                                }
                              }
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

